package http

import (
	"errors"
	"strings"

	"github.com/gogf/gf/net/ghttp"

	"websocket/lib/auth"
)

const (
	ctxUserKey          = `http.auth.user`
	pageKey             = `page`
	pageSizeKey         = `pageSize`
)

// Page 获取分页参数
func Page(r *ghttp.Request) (int, int) {
	page, pageSize := r.GetInt(pageKey, 1), r.GetInt(pageSizeKey, 10)
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	return page, pageSize
}

// JwtToken 获取jwt授权token
func JwtToken(r *ghttp.Request) (string, error) {
	token := r.GetString("__token")
	if token == "" {
		if s := strings.Split(r.Header.Get("Authorization"), " "); len(s) == 2 {
			token = s[1]
		}
	}
	if token == "" {
		return ``, errors.New(`jwt token 参数错误`)
	}
	return token, nil
}

// SetUser 设置请求上下文用户
func SetUser(r *ghttp.Request, user *auth.User) {
	r.SetCtxVar(ctxUserKey, user)
}

// GetUser 获取请求上下文用户
func GetUser(r *ghttp.Request) *auth.User {
	ctxVar := r.GetCtxVar(ctxUserKey)
	if ctxVar == nil {
		return nil
	}

	if user, ok := ctxVar.Val().(*auth.User); ok {
		return user
	}
	return nil
}

// MustGetUser 获取请求上下文机构账户
func MustGetUser(r *ghttp.Request) *auth.User {
	user := GetUser(r)
	if user == nil {
		panic(errors.New(`用户未登录`))
	}
	return user
}

// RedirectGuest 跳转，并记录回跳地址
func RedirectGuest(r *ghttp.Request, to string, back string, code ...int) {
	_ = r.Session.Set(`http.redirect.back`, back)
	r.Response.RedirectTo(to, code...)
}

// RedirectToIntended 回跳到之前记录的地址
func RedirectToIntended(r *ghttp.Request) {
	back := r.Session.GetString(`http.redirect.back`, `/`)
	r.Response.RedirectTo(back)
}

// WantJson 是否是json请求
func WantJson(r *ghttp.Request) bool {
	if r.IsAjaxRequest() {
		return true
	}

	accept := r.Header.Get("Accept")
	if accept == `*/*` || accept == `*` || strings.Contains(accept, `json`) {
		return true
	}

	return strings.Contains(r.Header.Get(`Content-Type`), `json`)
}
